package cn.bby.tools.actions.str.convert;

import cn.bby.tools.actions.str.BaseStringProcessAction;
import cn.bby.tools.dialog.SingleCheckDialog;
import cn.bby.tools.service.StateManagementService;
import cn.bby.tools.utils.SimpleStringUtil;
import cn.bby.tools.utils.split.LinkWordSplitUtilImpl;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

/**
 * @author ben
 * @since 2025/9/24 21:50
 */
public class IdentifyWord extends BaseStringProcessAction {
    private final LinkWordSplitUtilImpl wordSplitUtil = LinkWordSplitUtilImpl.getInstance();
    Map<String, Function<List<String>, String>> map = Map.of(
            "message.ToSmallCamel", SimpleStringUtil::toSmallCamel,
            "message.ToBigCamel", SimpleStringUtil::toBigCamel,
            "message.ToUnderlineLower", SimpleStringUtil::toUnderlineLower,
            "message.ToUnderlineUpper", SimpleStringUtil::toUnderlineUpper,
            "message.ToWord", SimpleStringUtil::toWord
    );
    private final static List<String> selectedList = List.of(
            "message.ToSmallCamel",
            "message.ToBigCamel",
            "message.ToUnderlineLower",
            "message.ToUnderlineUpper",
            "message.ToWord"
    );
    private final IdentifyWordState state = StateManagementService.getInstanceState().identifyWordState;
    public IdentifyWord() {
        if (!state.customWords.isEmpty()) {
            wordSplitUtil.addWords(state.customWords);
        }
    }

    @Override
    public String process(@NotNull AnActionEvent e, String selectedText) {
        Project project = e.getProject();
        int defaultSelId = state.selectedIndex;
        SingleCheckDialog dialog = new SingleCheckDialog(project,
                "请选择输出格式", selectedList, defaultSelId);
        dialog.showAndGet();
        state.selectedIndex = dialog.getSelectedIndex();
        if (!dialog.isOK()) {
            return selectedText;
        }
        int selectedIndex = dialog.getSelectedIndex();
        if (selectedIndex >= selectedList.size() || selectedIndex < 0) {
            return selectedText;
        }
        String selected = selectedList.get(selectedIndex);
        List<String> res = wordSplitUtil.doSplit(selectedText);
        if (res.isEmpty()) {
            return selectedText;
        }
        return map.get(selected).apply(res);
    }

    public static class IdentifyWordState {
        public int selectedIndex = 0;

        public Set<String> customWords = new HashSet<>();
    }
}
